package com.engine.salary.web;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.salaryBill.dto.*;
import com.engine.salary.entity.salaryBill.param.*;
import com.engine.salary.enums.salarybill.SalarySendStatusEnum;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.sys.enums.PayrollCheckTypeEnum;
import com.engine.salary.util.ResponseResult;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.wrapper.SalaryBillBaseSetWrapper;
import com.engine.salary.wrapper.SalarySendWrapper;
import com.engine.salary.wrapper.SalaryTemplateWrapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.general.BaseBean;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 工资单
 */
@Slf4j
public class SalaryBillController {
    private final Boolean isLog = "true".equals(new BaseBean().getPropValue("hrmSalary", "log"));

    private SalaryTemplateWrapper getSalaryTemplateWrapper(User user) {
        return ServiceUtil.getService(SalaryTemplateWrapper.class, user);
    }

    private SalarySendWrapper getSalarySendWrapper(User user) {
        return ServiceUtil.getService(SalarySendWrapper.class, user);
    }

    private SalaryBillBaseSetWrapper getSalaryBillBaseSetWrapper(User user) {
        return ServiceUtil.getService(SalaryBillBaseSetWrapper.class, user);
    }


    /******** 工资单模板 start ***********************************************************************************************/
    /**
     * 工资单模板列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/template/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String templateList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryTemplateQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryTemplateQueryParam, PageInfo<SalaryTemplateListDTO>>(user).run(getSalaryTemplateWrapper(user)::list, queryParam);
    }

    /**
     * 获取工资单模板基础设置表单
     *
     * @param id
     * @return
     */
    @GET
    @Path("/template/getBaseForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getBaseForm(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, SalaryTemplateBaseFormDTO>(user).run(getSalaryTemplateWrapper(user)::getBaseForm, id);
    }

    /**
     * 获取工资单模板显示设置表单
     *
     * @param id
     * @return
     */
    @GET
    @Path("/template/getShowForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getShowForm(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, SalaryTemplateShowFormDTO>(user).run(getSalaryTemplateWrapper(user)::getShowForm, id);
    }

    /**
     * 设置工资单模板薪资项显示名称
     *
     * @return
     */
    @POST
    @Path("/template/saveItemShowName")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveItemShowName(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody List<SalaryBillItemNameSaveParam> param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<List<SalaryBillItemNameSaveParam>, String>(user).run(getSalaryTemplateWrapper(user)::saveItemShowName, param);
    }

    /**
     * 获取薪资项目设置
     *
     * @param salarySobId
     * @return
     */
    @GET
    @Path("/template/getSalaryItemSet")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSalaryItemSet(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("salarySobId") Long salarySobId) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, List<SalaryTemplateSalaryItemSetListDTO>>(user).run(getSalaryTemplateWrapper(user)::getSalaryItemSet, salarySobId);
    }

    /**
     * 获取短信薪资项目设置
     *
     * @param salarySobId
     * @return
     */
    @GET
    @Path("/template/getSmsSalaryItemSet")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSmsSalaryItemSet(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("salarySobId") Long salarySobId) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, List<SalaryTemplateSalaryItemSetListDTO>>(user).run(getSalaryTemplateWrapper(user)::getSmsSalaryItemSet, salarySobId);
    }

    /**
     * 获取可用的薪资项目
     */
    @POST
    @Path("/template/getAvailableSalaryGroupSet")
    @Produces(MediaType.APPLICATION_JSON)
    public String getAvailableSalaryGroupSet(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                             @RequestBody SalaryBillSalaryGroupQueryParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryBillSalaryGroupQueryParam, List<SalaryTemplateSalaryItemSetListDTO>>(user)
                .run(getSalaryTemplateWrapper(user)::getSalaryGroupSet, param);
    }

    /**
     * 获取可用的薪资项目
     */
    @POST
    @Path("/template/getAvailableSalaryItemSet")
    @Produces(MediaType.APPLICATION_JSON)
    public String getAvailableSalaryItemSet(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                            @RequestBody SalaryBillSalaryItemQueryParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryBillSalaryItemQueryParam, List<SalaryTemplateSalaryItemListDTO>>(user)
                .run(getSalaryTemplateWrapper(user)::getSalaryItemSetGrouped, param);
    }

    /**
     * 获取工资单模板补发设置表单
     *
     * @return
     */
    @POST
    @Path("/template/getReplenishForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getReplenishForm(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody ReplenishFormQueryParam replenishFormQueryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<ReplenishFormQueryParam, SalaryTemplateReplenishFormDTO>(user).run(getSalaryTemplateWrapper(user)::getReplenishForm, replenishFormQueryParam);
    }


    /**
     * 工资单模板默认使用
     *
     * @param defaultUseParam
     * @return
     */
    @POST
    @Path("/template/defaultUse")
    @Produces(MediaType.APPLICATION_JSON)
    public String defaultUse(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryTemplateDefaultUseParam defaultUseParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryTemplateDefaultUseParam, List<SalaryTemplateSalaryItemSetListDTO>>(user).run(getSalaryTemplateWrapper(user)::defaultUse, defaultUseParam);
    }

    /**
     * 新建工资单模板
     *
     * @param saveParam
     * @return
     */
    @POST
    @Path("/template/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String save(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryTemplateSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryTemplateSaveParam, String>(user).run(getSalaryTemplateWrapper(user)::save, saveParam);
    }

    /**
     * 编辑工资单模板
     *
     * @param saveParam
     * @return
     */
    @POST
    @Path("/template/update")
    @Produces(MediaType.APPLICATION_JSON)
    public String update(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryTemplateSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryTemplateSaveParam, String>(user).run(getSalaryTemplateWrapper(user)::update, saveParam);
    }

    /**
     * 复制工资单模板
     *
     * @param copyParam
     * @return
     */
    @POST
    @Path("/template/copy")
    @Produces(MediaType.APPLICATION_JSON)
    public String copy(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryTemplateCopyParam copyParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryTemplateCopyParam, String>(user).run(getSalaryTemplateWrapper(user)::copy, copyParam);
    }

    /**
     * 删除工资单模板
     *
     * @param ids
     * @return
     */
    @POST
    @Path("/template/delete")
    @Produces(MediaType.APPLICATION_JSON)
    public String delete(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new SalaryRunTimeException("参数错误");
        }
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Collection<Long>, String>(user).run(getSalaryTemplateWrapper(user)::delete, ids);
    }

    /**
     * 获取薪资账套下拉列表
     *
     * @return
     */
    @POST
    @Path("/template/selectSalarySobList")
    @Produces(MediaType.APPLICATION_JSON)
    public String selectSalarySobList(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<>(user).run(getSalaryTemplateWrapper(user)::selectSalarySobList);
    }

    /**
     * 获取补发规则设置下拉列表
     *
     * @return
     */
    @GET
    @Path("/template/getReplenishRuleSetOptions")
    @Produces(MediaType.APPLICATION_JSON)
    public String getReplenishRuleSetOptions(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("salarySobId") Long salarySobId) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, List<Map<String, String>>>(user).run(getSalaryTemplateWrapper(user)::getReplenishRuleSetOptions, salarySobId);
    }


    /**
     * 获取租户名
     *
     * @return
     */
//    @POST
//    @Path("/template/getTenantName")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String getTenantName(@Context HttpServletRequest request, @Context HttpServletResponse response) {
//        return WeaResult.success(TenantContext.getCurrentTenant().getTenantName());
//    }
    /******** 工资单模板 end ***********************************************************************************************/

    /******** 工资单发放 start ***********************************************************************************************/
    /**
     * 工资单发放列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalarySendQueryParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::list, queryParam);
    }

    /**
     * 工资单发放基本信息
     *
     * @return
     */
    @GET
    @Path("/send/getBaseInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public String getBaseInfo(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, SalarySendBaseInfoDTO>(user).run(getSalarySendWrapper(user)::getBaseInfo, id);
    }

    /**
     * 预览工资单
     *
     * @param param
     * @return
     */
    @POST
    @Path("/preview")
    @Produces(MediaType.APPLICATION_JSON)
    public String preview(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryPreviewParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryPreviewParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::preview, param);
    }

    /**
     * 工资单发放信息列表的高级搜索
     *
     * @return
     */
    @GET
    @Path("/send/getInfoSearchCondition")
    @Produces(MediaType.APPLICATION_JSON)
    public String getInfoSearchCondition(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<>(user).run(getSalarySendWrapper(user)::getInfoSearchCondition);
    }

    /**
     * 工资单发放信息列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/infoList")
    @Produces(MediaType.APPLICATION_JSON)
    public String infoList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendInfoQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        if (StringUtils.isNotBlank(queryParam.getDepartmentIdStr())) {
            queryParam.setDepartmentIds(Arrays.stream(StringUtils.split(queryParam.getDepartmentIdStr(), ",")).map(Long::valueOf).collect(Collectors.toList()));
        }
        if (StringUtils.isNotBlank(queryParam.getSubCompanyIdStr())) {
            queryParam.setSubCompanyIds(Arrays.stream(StringUtils.split(queryParam.getSubCompanyIdStr(), ",")).map(Long::valueOf).collect(Collectors.toList()));
        }
        return new ResponseResult<SalarySendInfoQueryParam, PageInfo<SalarySendInfoListDTO>>(user).run(getSalarySendWrapper(user)::infoList, queryParam);
    }

    /**
     * 工资单发放信息合计行
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/sum")
    @Produces(MediaType.APPLICATION_JSON)
    public String sumSendResult(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendInfoQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalarySendInfoQueryParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::sumSendResult, queryParam);
    }

    /**
     * 导出-工资单发放信息列表
     *
     * @return
     */
    @POST
    @Path("/send/exportInfoList")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportInfoList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendInfoQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);

        XSSFWorkbook workbook = getSalarySendWrapper(user).exportInfoList(queryParam);

        String fileName = "工资单发放信息" + LocalDate.now();
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };

        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }


    /**
     * 工资单批量发放信息列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/batchSendInfoList")
    @Produces(MediaType.APPLICATION_JSON)
    public String batchSendInfoList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendInfoQueryParam queryParam) {
        // 包含未发送、已撤回
        queryParam.setSendStatuss(Arrays.asList(SalarySendStatusEnum.UNSEND.getValue(), SalarySendStatusEnum.WITHDRAW.getValue()));
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalarySendInfoQueryParam, PageInfo<SalarySendInfoListDTO>>(user).run(getSalarySendWrapper(user)::infoList, queryParam);

//        WeaTable<SalarySendInfoListDTO> weaTable = salarySendWrapper.infoList(queryParam, UserContext.getCurrentEmployeeId(), TenantContext.getCurrentTenantKey());
//        weaTable.setOperatesPermission(new LinkedList<>());
//        weaTable.setOperates(new LinkedList<>());
//        return WeaResult.success(weaTable);
    }

    /**
     * 工资单批量撤回信息列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/batchWithdrawInfoList")
    @Produces(MediaType.APPLICATION_JSON)
    public String batchWithdrawInfoList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendInfoQueryParam queryParam) {
        // 包含已发送
        queryParam.setSendStatuss(Arrays.asList(SalarySendStatusEnum.ALREADYSEND.getValue()));
        User user = HrmUserVarify.getUser(request, response);

        return new ResponseResult<SalarySendInfoQueryParam, PageInfo<SalarySendInfoListDTO>>(user).run(getSalarySendWrapper(user)::infoList, queryParam);
    }

    /**
     * 工资单发放
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/grant")
    @Produces(MediaType.APPLICATION_JSON)
    public String grant(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendGrantParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalarySendGrantParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::grant, queryParam);
    }

    /**
     * 工资单撤回
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/withdraw")
    @Produces(MediaType.APPLICATION_JSON)
    public String withdraw(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendWithdrawParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalarySendWithdrawParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::withdraw, queryParam);
    }

    /**
     * 工资单发放详情列表的高级搜索
     *
     * @return
     */
    @POST
    @Path("/send/getDetailSearchCondition")
    @Produces(MediaType.APPLICATION_JSON)
    public String getDetailSearchCondition(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Object, Map<String, Object>>(user).run(getSalarySendWrapper(user)::getDetailSearchCondition);
    }

    /**
     * 工资单发放详情列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/send/detailList")
    @Produces(MediaType.APPLICATION_JSON)
    public String detailList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalarySendDetailListQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        // 处理入参复用方法
        SalarySendDetailQueryParam detailQueryParam = SalarySendDetailQueryParam.builder()
                .userId(queryParam.getUserId())
                .departmentIds(CollectionUtils.isEmpty(queryParam.getDepartmentIds()) ? null : queryParam.getDepartmentIds())
                .salarySendId(queryParam.getSalarySendId())
                .mergeCountTax(queryParam.getMergeCountTax())
                .positionIds(SalaryEntityUtil.isNullOrEmpty(queryParam.getPosition()) ? null : Collections.singletonList(queryParam.getPosition()))
                .taxAgentId(queryParam.getTaxAgent())
                .username(queryParam.getUsername())
                .userstatus(queryParam.getUserstatus()).build();
        detailQueryParam.setCurrent(queryParam.getCurrent());
        detailQueryParam.setPageSize(queryParam.getPageSize());

        if (StringUtils.isNotBlank(queryParam.getSubCompanyIdStr())) {
            detailQueryParam.setSubCompanyIds(Arrays.asList(StringUtils.split(queryParam.getSubCompanyIdStr(), ",")).stream().map(Long::new).collect(Collectors.toList()));
        }
        if (StringUtils.isNotBlank(queryParam.getDepartmentIdStr())) {
            detailQueryParam.setDepartmentIds(Arrays.asList(StringUtils.split(queryParam.getDepartmentIdStr(), ",")).stream().map(Long::new).collect(Collectors.toList()));
        }
        return new ResponseResult<SalarySendDetailQueryParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::detailList, detailQueryParam);
    }

    /**
     * 导出-工资单发放详情列表
     *
     * @return
     */
    @POST
    @Path("/send/exportDetailList")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response exportDetailList(@Context HttpServletRequest request, @Context HttpServletResponse response,@RequestBody SalarySendDetailQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);

        // SalarySendDetailQueryParam queryParam = new SalarySendDetailQueryParam();
        // String salarySendId = request.getParameter("salarySendId");
        // String ids = request.getParameter("ids");
        // if (StringUtils.isNotBlank(ids)) {
        //     queryParam.setIds(Arrays.asList(ids.split(",")).stream().map(Long::new).collect(Collectors.toList()));
        // }
        // if (StringUtils.isNotBlank(salarySendId)) {
        //     queryParam.setSalarySendId(Long.parseLong(salarySendId));
        // }
        XSSFWorkbook workbook = getSalarySendWrapper(user).exportDetailList(queryParam);

        String fileName = "工资单发放详情列表" + LocalDate.now();
        try {
            fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        StreamingOutput output = outputStream -> {
            workbook.write(outputStream);
            outputStream.flush();
        };

        response.setContentType("application/octet-stream");
        return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
    }

//    @GET
//    @Path("/exportPdf")
//    @Produces({"application/pdf"})
//    public Response getPDF(@Context HttpServletRequest request, @Context HttpServletResponse response)  {
//
//        File f = new File("D:\\gzd\\2023-02\\1695104948592.pdf");
//        return Response.ok(f, "application/pdf").build();
//
//    }


    /**
     * 下载pdf前先进行校验 生成
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/genPdfBeforeExport")
    @Produces(MediaType.APPLICATION_JSON)
    public String genPdfBeforeExport(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        SalaryExportPdfParam salaryExportPdfParam = new SalaryExportPdfParam();
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            salaryExportPdfParam.setId(Long.valueOf(id));
        }
        String salarySendId = request.getParameter("salarySendId");
        if (StringUtils.isNotBlank(salarySendId)) {
            salaryExportPdfParam.setSalarySendId(Long.valueOf(salarySendId));
        }
        return new ResponseResult<SalaryExportPdfParam, String>(user).run(getSalarySendWrapper(user)::genPdfBeforeExport, salaryExportPdfParam);
    }

    @GET
    @Path("/exportPdf")
    public Response downloadPdfFile(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        SalaryExportPdfParam salaryExportPdfParam = new SalaryExportPdfParam();
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            salaryExportPdfParam.setId(Long.valueOf(id));
        }
        String salarySendId = request.getParameter("salarySendId");
        if (StringUtils.isNotBlank(salarySendId)) {
            salaryExportPdfParam.setSalarySendId(Long.valueOf(salarySendId));
        }

        StreamingOutput fileStream = new StreamingOutput() {
            @Override
            public void write(java.io.OutputStream output) throws IOException, WebApplicationException {
                String pdfPath = getSalarySendWrapper(user).exportPdf(salaryExportPdfParam);
                java.nio.file.Path path = Paths.get(pdfPath);
                byte[] data = Files.readAllBytes(path);
                output.write(data);
                output.flush();
            }
        };

        String fileName = "工资单";
        try {
            fileName = URLEncoder.encode(fileName + ".pdf", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return Response
                .ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename =" + fileName)
                .build();
    }

    /**
     * 我的工资单列表
     *
     * @param
     * @return
     */
    @POST
    @Path("/getToken")
    @Produces(MediaType.APPLICATION_JSON)
    public String getToken(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryBillGetTokenParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryBillGetTokenParam, Map<String, String>>(user).run(getSalarySendWrapper(user)::getToken, param);
    }

    /**
     * 我的工资单列表
     *
     * @param queryParam
     * @return
     */
    @POST
    @Path("/mySalaryBillList")
    @Produces(MediaType.APPLICATION_JSON)
    public String mySalaryBillList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryBillQueryParam queryParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryBillQueryParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::mySalaryBillList, queryParam);
    }

    /**
     * 我的工资单
     *
     * @param salaryInfoId
     * @return
     */
    @GET
    @Path("/mySalaryBill")
    @Produces(MediaType.APPLICATION_JSON)
    public String mySalaryBill(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "salaryInfoId") Long salaryInfoId) {
        User user = null;
        user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, Map<String, Object>>(user).run(getSalarySendWrapper(user)::mySalaryBill, salaryInfoId);
    }


    /**
     * 二开 工资单展开详情
     *
     * @param param
     * @return
     */
    @POST
    @Path("/listDetailSalaryBill")
    @Produces(MediaType.APPLICATION_JSON)
    public String listDetailSalaryBill(@Context HttpServletRequest request, @Context HttpServletResponse response, EkSalaryBillDetailQueryParam param) {
        User user = null;
        user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<EkSalaryBillDetailQueryParam, List<Map<String, Object>>>(user).run(getSalarySendWrapper(user)::listDetailSalaryBill, param);
    }

    /**
     * 二开 奖金数据穿透
     *
     * @param param
     * @return
     */
    @POST
    @Path("/listJjfp")
    @Produces(MediaType.APPLICATION_JSON)
    public String listSalaryBillJjfp(@Context HttpServletRequest request, @Context HttpServletResponse response, EkSalaryBillDetailQueryParam param) {
        User user = null;
        user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<EkSalaryBillDetailQueryParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::listSalaryBillJjfp, param);
    }

    /**
     * 二开 劳务数据穿透
     *
     * @param param
     * @return
     */
    @POST
    @Path("/listLwf")
    @Produces(MediaType.APPLICATION_JSON)
    public String listSalaryBillLwf(@Context HttpServletRequest request, @Context HttpServletResponse response, EkSalaryBillDetailQueryParam param) {
        User user = null;
        user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<EkSalaryBillDetailQueryParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::listSalaryBillLwf, param);
    }

    /**
     * 确认工资单
     *
     * @param salaryInfoId
     * @return
     */
    @GET
    @Path("/confirmSalaryBill")
    @Produces(MediaType.APPLICATION_JSON)
    public String confirmSalaryBill(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "salaryInfoId") Long salaryInfoId) {
        User user = null;
        String recipient = request.getParameter("recipient");
        String em_auth_userid = request.getParameter("em_auth_userid");
        log.info("salary recipient: {}  em_auth_userid: {}", recipient, em_auth_userid);
        if (StringUtils.isNotBlank(recipient) && NumberUtils.isCreatable(recipient)) {
            user = new User(Integer.parseInt(recipient));
        } else if (StringUtils.isNotBlank(em_auth_userid) && NumberUtils.isCreatable(em_auth_userid)) {
            user = new User(Integer.parseInt(em_auth_userid));
        } else {
            user = HrmUserVarify.getUser(request, response);
        }
        return new ResponseResult<Long, Map<String, Object>>(user).run(getSalarySendWrapper(user)::confirmSalaryBill, salaryInfoId);
    }

    /**
     * 工资单反馈
     *
     * @param salaryInfoId
     * @return
     */
    @GET
    @Path("/feedBackSalaryBill")
    @Produces(MediaType.APPLICATION_JSON)
    public String feedBackSalaryBill(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "salaryInfoId") Long salaryInfoId) {
        User user = null;
        String recipient = request.getParameter("recipient");
        String em_auth_userid = request.getParameter("em_auth_userid");
        log.info("salary recipient: {}  em_auth_userid: {}", recipient, em_auth_userid);
        if (StringUtils.isNotBlank(recipient) && NumberUtils.isCreatable(recipient)) {
            user = new User(Integer.parseInt(recipient));
        } else if (StringUtils.isNotBlank(em_auth_userid) && NumberUtils.isCreatable(em_auth_userid)) {
            user = new User(Integer.parseInt(em_auth_userid));
        } else {
            user = HrmUserVarify.getUser(request, response);
        }
        return new ResponseResult<Long, Map<String, Object>>(user).run(getSalarySendWrapper(user)::feedBackSalaryBill, salaryInfoId);
    }
    /******** 工资单发放 end ***********************************************************************************************/

    /**
     * 获取验证方式
     *
     * @return
     */
    @GET
    @Path("/payrollCheckType")
    @Produces(MediaType.APPLICATION_JSON)
    public String payrollCheckType(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SMSCodeSendParam, PayrollCheckTypeEnum>(user).run(getSalarySendWrapper(user)::payrollCheckType);
    }

    /**
     * 短信验证码
     *
     * @param param
     * @return
     */
    @POST
    @Path("/sendMobileCode")
    @Produces(MediaType.APPLICATION_JSON)
    public String sendSMSCode(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SMSCodeSendParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SMSCodeSendParam, Map<String, Object>>(user).run(getSalarySendWrapper(user)::sendMobileCode, param);
    }

    /**
     * 校验验证码
     *
     * @param request
     * @param response
     * @param param
     * @return
     */
    @POST
    @Path("/checkMobileCode")
    @Produces(MediaType.APPLICATION_JSON)
    public String checkMobileCode(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SMSCodeCheckParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SMSCodeCheckParam, Boolean>(user).run(getSalarySendWrapper(user)::checkMobileCode, param);
    }

    /******** 工资单基础设置 start ***********************************************************************************************/

    /**
     * 获取工资单基础设置表单
     *
     * @return
     */
    @GET
    @Path("/baseSet/getForm")
    @Produces(MediaType.APPLICATION_JSON)
//    @ApiOperation("获取工资单基础设置表单")
    public String getBaseSetForm(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<String, SalaryBaseSetFormDTO>(user).run(getSalaryBillBaseSetWrapper(user)::getBaseSetForm);
    }

    /**
     * 预览水印
     *
     * @return
     */
    @POST
    @Path("/baseSet/previewWaterMark")
    @Produces(MediaType.APPLICATION_JSON)
    public String getBaseSetForm(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryBaseSetSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryBaseSetSaveParam, String>(user).run(getSalaryBillBaseSetWrapper(user)::previewWaterMark, saveParam);
    }

    /**
     * 保存工资单基础设置
     *
     * @param saveParam 保存参数
     * @return
     */
    @POST
    @Path("/baseSet/save")
    @Produces(MediaType.APPLICATION_JSON)
//    @ApiOperation("保存工资单基础设置")
    public String saveBaseSet(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryBaseSetSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryBaseSetSaveParam, String>(user).run(getSalaryBillBaseSetWrapper(user)::saveBaseSet, saveParam);
    }
    /******** 工资单基础设置 end ***********************************************************************************************/


}
